import React, { PureComponent } from 'react';
import { findDOMNode } from 'react-dom';
import { connect } from 'dva';
import { Card, Input, Button, Modal, Form, List } from 'antd';
import { imageOrigin } from '../config';
import ImageUploader from '@/components/ImageUploader';
import ImagesUploader from '@/components/ImagesUploader';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Result from '@/components/Result';
import styles from './SetByMerchant.less';

const FormItem = Form.Item;

@connect(({ setByMerchant, loading }) => ({
  setByMerchant,
  loading: loading.models.list,
}))
@Form.create()
class SetByMerchant extends PureComponent {
  state = {
    visible: false,
    done: false,
    previewVisible: false,
    previewImage: '',
  };

  formLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 13 },
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'setByMerchant/fetch',
    });
  }

  showModal = () => {
    this.setState({
      visible: true,
      current: undefined,
    });
  };

  handleCancels = () => this.setState({ previewVisible: false });

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  showEditModal = (item, index) => {
    this.setState({
      visible: true,
      current: item,
      editableIndex: index,
    });
  };

  handleDone = () => {
    setTimeout(() => this.addBtn.blur(), 0);
    this.setState({
      done: false,
      visible: false,
    });
  };

  handleCancel = () => {
    setTimeout(() => this.addBtn.blur(), 0);
    this.setState({
      visible: false,
    });
  };

  isOnSelect = value => {
    if (value !== 'present') {
      this.setState({});
    } else {
      this.setState({});
    }
  };

  handleSubmit = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { editableIndex } = this.state;
    const storeId = Number(localStorage.getItem('storeId'));
    setTimeout(() => this.addBtn.blur(), 0);
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        done: true,
      });
      dispatch({
        type: 'setByMerchant/update',
        payload: {
          ...fieldsValue,
          storeId,
          editableIndex,
        },
      });
    });
  };

  deleteItem = (id, currentIndex) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'setByMerchant/remove',
      payload: { id, currentIndex },
    });
  };

  handleSearch = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'setByMerchant/search',
      payload: value,
    });
  };

  render() {
    const {
      setByMerchant: { data },
      loading,
    } = this.props;
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { visible, done, previewVisible, previewImage, current = {} } = this.state;

    const modalFooter = done
      ? { footer: null, onCancel: this.handleDone }
      : { okText: '保存', onOk: this.handleSubmit, onCancel: this.handleCancel };

    const cardList = data ? (
      <Card
        className={styles.card}
        hoverable
        cover={
          <img
            alt={data.name}
            src={`${imageOrigin}${data.imageHash}`}
            style={{ width: '225px', height: '220px' }}
          />
        }
      >
        <div className={styles.cardItemContent}>
          <span>店铺封面</span>
        </div>
      </Card>
    ) : null;
    const cardList2 = data ? (
      <Card
        className={styles.card}
        hoverable
        cover={
          <img
            alt={data.name}
            src={`${imageOrigin}${data.fileHash}`}
            style={{ width: '225px', height: '220px' }}
          />
        }
      >
        <div className={styles.cardItemContent}>
          <span>营业执照</span>
        </div>
      </Card>
    ) : null;
    const cardList3 = data.storeImages ? (
      <List
        rowKey="id"
        loading={loading}
        grid={{ gutter: 24, xl: 4, lg: 3, md: 3, sm: 2, xs: 1 }}
        dataSource={data.storeImages}
        renderItem={item => (
          <List.Item>
            <Card
              className={styles.card}
              hoverable
              cover={
                <img
                  alt={item.createdAt}
                  src={`${imageOrigin}${item.imageHash}`}
                  style={{ width: '215px', height: '220px' }}
                />
              }
            >
              <div className={styles.cardItemContent}>
                <span>店铺详情图</span>
              </div>
            </Card>
          </List.Item>
        )}
      />
    ) : null;

    const cardInfo = data ? (
      <div style={{ background: 'white', padding: '30px' }}>
        <Card title={`${data.name}`} bordered={false} style={{ width: 300 }}>
          <p>电话:{`${data.phone}`}</p>
          <p>地址:{`${data.address}`}</p>
          <p>佣金比例:{`${data.commissionRatio}`}</p>
        </Card>
      </div>
    ) : null;

    const getModalContent = () => {
      if (done) {
        return (
          <Result
            type="success"
            title="操作成功"
            description="已确认修改"
            actions={
              <Button type="primary" onClick={this.handleDone}>
                知道了
              </Button>
            }
            className={styles.formResult}
          />
        );
      }
      // const imageUrl = this.state.imageUrl;
      return (
        <Form onSubmit={this.handleSubmit}>
          <FormItem label="店铺封面尺寸" {...this.formLayout}>
            <span>1000*1000</span>
          </FormItem>
          <FormItem label="店铺封面" {...this.formLayout}>
            {getFieldDecorator('imageHash', {
              rules: [{ required: false, message: '请选择商品封面' }],
              initialValue: `${data.imageHash}`,
            })(<ImageUploader />)}
            <Modal footer={null} onCancel={this.handleCancelsTop}>
              <img alt="这是封面" style={{ width: '50%' }} />
            </Modal>
          </FormItem>
          <FormItem label="店铺地址" {...this.formLayout}>
            {getFieldDecorator('address', {
              rules: [{ required: true, message: '名称不能超过十七个字符', max: 17 }],
              initialValue: data.address,
            })(<Input placeholder="请输入店铺地址" />)}
          </FormItem>
          <FormItem label="联系电话" {...this.formLayout}>
            {getFieldDecorator('phone', {
              rules: [{ required: true, message: '名称不能超过十一个字符', max: 11 }],
              initialValue: data.phone,
            })(<Input placeholder="请输入联系电话" />)}
          </FormItem>
          <FormItem label="营业执照" {...this.formLayout}>
            {getFieldDecorator('fileHash', {
              rules: [{ required: false, message: '请选择营业执照' }],
              initialValue: `${data.fileHash}`,
            })(<ImageUploader />)}
            <Modal footer={null} onCancel={this.handleCancelsTop}>
              <img alt="这是营业执照" style={{ width: '50%' }} />
            </Modal>
          </FormItem>
          <FormItem label="店铺详情图尺寸" {...this.formLayout}>
            <span>1920*1080</span>
          </FormItem>
          <FormItem {...this.formLayout} label="店铺详情图">
            {getFieldDecorator('imageHashes', {
              rules: [{ message: '请选择店铺详情图！', type: 'array' }],
            })(<ImagesUploader />)}
            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancels}>
              <img alt="example" style={{ width: '50%' }} src={previewImage} />
            </Modal>
          </FormItem>
        </Form>
      );
    };
    return (
      <PageHeaderWrapper>
        <div className={styles.standardList}>
          <Card
            className={styles.listCard}
            bordered={false}
            title="基础设置"
            style={{ marginTop: 24 }}
            bodyStyle={{ padding: '0 32px 40px 32px' }}
          >
            <Button
              type="dashed"
              style={{ width: '100%', marginBottom: 8 }}
              icon="plus"
              onClick={this.showModal}
              ref={component => {
                /* eslint-disable */
                this.addBtn = findDOMNode(component);
                /* eslint-enable */
              }}
            >
              设置
            </Button>
            <card />
            <div className={styles.coverCardList}>
              <div className={styles.cardList}>{cardInfo}</div>
              <div className={styles.cardList}>{cardList}</div>
              <div className={styles.cardList}>{cardList2}</div>
              <div className={styles.cardList}>{cardList3}</div>
            </div>
          </Card>
        </div>
        <Modal
          title={done ? null : `设置${current ? '添加' : '编辑'}`}
          className={styles.standardListForm}
          width={640}
          bodyStyle={done ? { padding: '72px 0' } : { padding: '28px 0 0' }}
          destroyOnClose
          visible={visible}
          {...modalFooter}
        >
          {getModalContent()}
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default SetByMerchant;
